package cn.tedu.csmall.order.webapi.service.impl;

import cn.tedu.csmall.cart.service.ICartService;
import cn.tedu.csmall.commons.exception.CoolSharkServiceException;
import cn.tedu.csmall.commons.pojo.order.dto.OrderAddDTO;
import cn.tedu.csmall.commons.pojo.order.entity.Order;

import cn.tedu.csmall.commons.pojo.stock.dto.StockReduceCountDTO;
import cn.tedu.csmall.commons.restful.JsonPage;
import cn.tedu.csmall.commons.restful.ResponseCode;
import cn.tedu.csmall.order.service.IOrderService;
import cn.tedu.csmall.order.webapi.mapper.OrderMapper;
import cn.tedu.csmall.stock.service.IStockService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

// order模块是具备生产者特征的，它会被
@DubboService
@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    // 添加@DubboReference注解，表示当前业务逻辑层要消费其他模块的业务
    // 注解后声明的应该是Dubbo注册到nacos其他模块声明的业务逻辑层接口
    // 业务逻辑层接口的实现类会在Dubbo框架下自动获取
    @DubboReference
    private IStockService stockService;
    @DubboReference
    private ICartService cartService;

    @Override
    public void orderAdd(OrderAddDTO orderAddDTO) {
        // 1.先减去订单中商品的库存数(调用Stock模块减少库存的方法)
        StockReduceCountDTO stockReduceCountDTO = new StockReduceCountDTO();
        stockReduceCountDTO.setCommodityCode(orderAddDTO.getCommodityCode());
        stockReduceCountDTO.setReduceCount(orderAddDTO.getCount());

        stockService.reduceCommodityCount(stockReduceCountDTO);
        // 2.从购物车中删除用户选中的商品(调用Cart模块删除购物车中商品的方法)
        cartService.deleteUserCart(orderAddDTO.getUserId(), orderAddDTO.getCommodityCode());
        // 3.新增当前订单信息
        Order order = new Order();
        BeanUtils.copyProperties(orderAddDTO, order);
        int row = orderMapper.insertOrder(order);
        log.info("新增订单信息为:{}",order);

        // 为了实现seata的回滚效果，在这里随机抛出异常
//        if (Math.random()<0.5){
//            // 抛出异常
//            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR, "发生随机异常");
//        }
    }

    // 分页查询所有订单的业务逻辑层方法
    public JsonPage<Order> getAllOrdersByPage(Integer page, Integer pageSize){
        // PageHelper框架实现分页的核心操作
        PageHelper.startPage(page, pageSize);
        List<Order> list = orderMapper.findAllOrders();
        return JsonPage.restPage(new PageInfo<>(list));
    }
}
